// 创建用户相关的小仓库
import { defineStore } from "pinia";
// 引入接口
import { reqLogin, reqUserInfo } from "@/api/user";
import type { loginForm, loginResponseData, userInfoResponseData } from "@/api/user/type";
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from "@/utils/token";
import { ref } from "vue";
import { constantRoute, asyncRoute, anyRoute } from "@/router/routes";
import { ElMessage } from "element-plus";
// 引入路由
import router from "@/router";
// 引入深拷贝方法
// @ts-ignore
// import cloneDeep from "lodash/cloneDeep";

// 创建用户小仓库
const useUserStore = defineStore("User", () => {
    const menuRoutes: any = ref<any>(constantRoute);
    // 用户个人信息
    const token = ref<string>(GET_TOKEN());
    const userId = ref<number>(-1);
    const userName = ref<string>("游客");
    const avatar = ref<string>("/user.webp");
    const intro = ref<string>("");
    const email = ref<string>("");

    async function userLogin(data: loginForm) {
        const result: loginResponseData = await reqLogin(data);
        if (result.code == 200 && typeof result.data == "object") {
            token.value = result.data.token;
            SET_TOKEN(token.value);
            return "ok";
        } else {
            return Promise.reject(new Error(result.data as string));
        }
    }

    async function userInfo() {
        const result: userInfoResponseData = await reqUserInfo();
        if (result.code == 200 && typeof result.data == "object") {
            userId.value = result.data.id;
            userName.value = result.data.name;
            avatar.value = result.data.avatar;
            intro.value = result.data.intro;
            email.value = result.data.email;
            // 用于获取相应权限异步路由
            const userAsyncRoute = asyncRoute;
            // 菜单的数据
            menuRoutes.value = constantRoute.concat(userAsyncRoute as any).concat(anyRoute as any);
            // 获取之后还要给路由注册上新路由
            [...userAsyncRoute, ...anyRoute].forEach((route: any) => {
                router.addRoute(route);
            });
            return "ok";
        } else {
            return Promise.reject(new Error(result.message));
        }
    }

    async function userLogout() {
        REMOVE_TOKEN();
        token.value = "";
        userName.value = "游客";
        avatar.value = "/user.webp";
        // 删除菜单列表
        menuRoutes.value = constantRoute;
        ElMessage.success("成功退出登录!");
    }

    return {
        token,
        userId,
        userName,
        avatar,
        email,
        intro,
        menuRoutes,
        userLogin,
        userLogout,
        userInfo,
    };
});

export default useUserStore;
